﻿using MediatR;
using Microsoft.OpenApi.Writers;
using RedDragon.Common.Domain.Manufacture;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.API.Application.Commands.Proccess;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.WorkCenter
{
    public class UpdApproveStateHandler : IRequestHandler<UpdApproveStateCommand, Result>
    {
        /// <summary>
        /// 工作表仓储
        /// </summary>
        public readonly IBaseRepository<WorkCenters> workCenterRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdApproveStateHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workCenterRepository"></param>
        /// <param name="logger"></param>
        public UpdApproveStateHandler(IBaseRepository<WorkCenters> workCenterRepository, ILogger<UpdApproveStateHandler> logger)
        {
            this.workCenterRepository = workCenterRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 审批状态中心
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(UpdApproveStateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var list = await (await workCenterRepository.GetAll()).Where(d => d.WorkCenterCode == request.WorkCenterCode).FirstAsync();
                if (list != null)
                {
                    list.ApproveState = request.ApproveState;
                }
                var res = workCenterRepository.Update(list);
                result.Code = (int)CommonErrorCode.Success;
                result.Data = list;
                result.Msg = "工作中心审批成功";
            }
            catch (Exception ex)
            {
                result.Msg = "工作中心审批失败" + ex.Message;
                logger.LogError("工作中心审批失败" + ex.Message);
            }
            return result;
        }
    }
}
